'use client'

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useRouter } from 'next/navigation';
import { toast } from '@/hooks/use-toast';
import { useEffect } from 'react';

export default function ChangePassword() {
  const [oldPassword, setOldPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const router = useRouter();

  // 检查登录状态
  useEffect(() => {
    const checkLoginStatus = async () => {
      try {
        const token = document.cookie
          .split('; ')
          .find(row => row.startsWith('admin_session='))?
          .split('=')[1];

        if (!token) {
          router.push('/admin/login');
          return;
        }

        const response = await fetch('/api/admin/auth', {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`,
          },
        });

        const data = await response.json();
        if (data.success && data.isLoggedIn) {
          setIsLoggedIn(true);
        } else {
          router.push('/admin/login');
        }
      } catch (error) {
        console.error('检查登录状态失败:', error);
        router.push('/admin/login');
      }
    };

    checkLoginStatus();
  }, [router]);

  const handleChangePassword = async (e: React.FormEvent) => {
    e.preventDefault();

    if (newPassword !== confirmPassword) {
      toast({ title: '两次输入的新密码不一致', variant: 'error' });
      return;
    }

    setLoading(true);

    try {
      const token = document.cookie
        .split('; ')
        .find(row => row.startsWith('admin_session='))?
        .split('=')[1];

      if (!token) {
        toast({ title: '未登录', variant: 'error' });
        router.push('/admin/login');
        return;
      }

      const response = await fetch('/api/admin/auth', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({ oldPassword, newPassword }),
      });

      const data = await response.json();

      if (data.success) {
        toast({ title: '密码更改成功', variant: 'success' });
        // 重置表单
        setOldPassword('');
        setNewPassword('');
        setConfirmPassword('');
      } else {
        toast({ title: data.message, variant: 'error' });
      }
    } catch (error) {
      console.error('更改密码失败:', error);
      toast({ title: '服务器错误', variant: 'error' });
    } finally {
      setLoading(false);
    }
  };

  if (!isLoggedIn) {
    return <div>加载中...</div>;
  }

  return (
    <div className="container mx-auto py-16 px-4">
      <div className="max-w-md mx-auto">
        <Card>
          <CardHeader>
            <CardTitle>更改管理员密码</CardTitle>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleChangePassword} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="oldPassword">旧密码</Label>
                <Input
                  id="oldPassword"
                  type="password"
                  placeholder="请输入旧密码"
                  value={oldPassword}
                  onChange={(e) => setOldPassword(e.target.value)}
                  required
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="newPassword">新密码</Label>
                <Input
                  id="newPassword"
                  type="password"
                  placeholder="请输入新密码"
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                  required
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="confirmPassword">确认新密码</Label>
                <Input
                  id="confirmPassword"
                  type="password"
                  placeholder="请再次输入新密码"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  required
                />
              </div>
              <Button type="submit" className="w-full" disabled={loading}>
                {loading ? '修改中...' : '修改密码'}
              </Button>
            </form>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}